<template>
	<!-- 表格工具编辑对话框	 -->
	<el-dialog title="编辑相应工具栏规则" :visible.sync="isEditable" :center="true" width="98%" @open="opendDialog" @close="closeDialog" :close-on-click-modal="false">
		<!-- 导航栏 -->
		<div class="crumbs">
            <el-breadcrumb separator="/">
                <el-breadcrumb-item><i class="el-icon-menu"></i>{{navInfo.workflowName}}</el-breadcrumb-item>
                <el-breadcrumb-item>{{navInfo.reportName}}</el-breadcrumb-item>
            </el-breadcrumb>
        </div>
		
		<!-- 查询表单 -->
		<el-form :inline="true" ref="formTool" :model="formTool" label-width="90px">
			<el-form-item label="字段名称" :rules="{type:'number', required: true, message: '请选择控件类型', trigger: 'change'}" prop="fieldId">
				<el-select size="small" v-model="formTool.fieldId" @change="changeValue" placeholder="字段名称">
					<el-option v-for="item in fieldData" :key="item.fieldId" :label="item.label" :value="item.fieldId"></el-option>
				</el-select>
			</el-form-item>

			<el-form-item label="类型" :rules="{required: true, message: '请选择控件类型', trigger: 'change'}" prop="type">
				<el-select size="small" v-model="formTool.type" placeholder="控件类型">
					<el-option label="文本输入框" value="rule-input"></el-option>
					<el-option label="数字输入框" value="rule-number"></el-option>
					<el-option label="时间选择器" value="rule-datepicker"></el-option>
					<el-option label="选择器" value="rule-select"></el-option>
				</el-select>
			</el-form-item>
			
			<el-form-item>
				<el-button type="success" icon="el-icon-arrow-down" plain @click="addInfo('formTool')">添加</el-button>
			</el-form-item>

		</el-form>
		<!-- 查询表单 End-->
		
		<!-- 工具栏数据表格 -->
		<el-table :data="toolTableData" border highlight-current-row height="300" size="mini" v-loading="listLoading" :fit="true" :show-overflow-tooltip="true" :stripe="true">
			<el-table-column type="index" align="center" width="35" ></el-table-column>
			<el-table-column prop="fieldId" align="center" label="标识"></el-table-column>
			<el-table-column prop="label" align="center" label="字段名称"></el-table-column>
			<el-table-column label="字段类型">
				<template scope="scope">
					<span v-show="!scope.row.isedit">{{scope.row.type}}</span>
					<el-select size="small"  v-show="scope.row.isedit" v-model="scope.row.type">
						<el-option label="文本输入框" value="rule-input"></el-option>
						<el-option label="数字输入框" value="rule-number"></el-option>
						<el-option label="时间选择器" value="rule-datepicker"></el-option>
						<el-option label="选择器" value="rule-select"></el-option>
					</el-select>
				</template>
			</el-table-column>
			<!-- 表格操作工具栏 -->
			<el-table-column label="操作" align="center" width="150">
				<template scope="scope">
					<!-- 韩内编辑 -->
					<el-button :type="!scope.row.isedit ? 'primary' : 'success'" size="small" @click="handleRowEdit(scope.$index, scope.row)">{{!scope.row.isedit ? '编辑' : '确定'}}</el-button>	
					<el-button type="info" v-show="scope.row.isedit" size="small" @click="cancelRowEdit(scope.$index, scope.row)">取消</el-button>	

					<!-- 删除提示tooltip -->
					<el-popover ref="popoverDelete" placement="top"  v-model="scope.row.visible">
						<p>确定要删除这条数据吗?</p>
						<div style="text-align: center;">
							<el-button size="mini" type="success" @click="scope.row.visible = false">取消</el-button>
							<el-button size="mini" type="danger" @click="handleRowDel(scope.$index, scope.row)">确定</el-button>
						</div>
						<el-button type="danger" v-show="!scope.row.isedit" size="small" slot="reference" @click="scope.row.visible = true">删除</el-button>
					</el-popover>
				</template>
			</el-table-column>
			<!-- 表格操作工具栏 End-->
		</el-table>
		<!-- 工具栏数据表格 End-->
		
		<!-- 工具栏预览 -->
		<el-form :inline="true" v-model="search" label-width="180px" class="preview-tool-form">
			<draggable v-model="toolComponents" @end="tabelSort">
				<li v-for="item in toolComponents" :is="item.component" :reset="reset" :toolInfo="item.toolInfo" v-on:message="getSearchValue" ></li>
			</draggable>
			<el-row style="text-align:center;margin-bottom:0px;">
				<el-form-item>
					<el-button type="primary" size="small">查询</el-button>
				</el-form-item>
				<el-form-item>
					<el-button type="info" size="small" @click="resetForm()">重置</el-button>
				</el-form-item>
			</el-row>
		</el-form>
		<!-- 工具栏预览 End-->

		<!-- 对话框底部工具栏 -->
		<span slot="footer" class="dialog-footer">
			<el-button type="info" @click="cancelEdit('formTool')">取消</el-button>
			<el-button type="primary" @click="finishedEdit">确定</el-button>
		</span>
		<!-- 对话框底部工具栏 End-->
	</el-dialog>
	<!-- 表格工具编辑对话框	 End-->
</template>

<script>
	/* 表单组件 */
	import formInput from './../form/input.vue'
	import formNumber from './../form/number.vue'
	import formSelect from './../form/select.vue'
	import formDatepicker from './../form/datepicker.vue'
	import draggable from 'vuedraggable'

	export default {
		name: 'ToolDialog',
		props: ['isConfigTool', 'configRow'],
		data(){
			return {
				// 启用编辑
				isEditable: this.isConfigTool,
				navInfo: this.configRow,

				// 表格加载动画
				listLoading: false,
				// 行内编辑属性缓存
				cacheRows: {},
				// 工具表格数据
				toolTableData: [],
				// 工具表格数据-删除缓存副本
				toolTableDataDeleted: [],

				// 表单
				formTool: {
					id: '',
					reportId: '',
					fieldId: '',
					fieldName: '',
					label: '',
					type: '',
					deletedType: false,
					isedit: false,
				},

				// 字段数据
				fieldData: [],

				// 工具栏预览
				toolComponents: [],

				// 拖拽状态
				drage: false,

				// 工具栏表单搜索对象
				search: {},
				// 工具栏表单重置状态
				reset: false
			}
		},
		mounted: function(){

		},
		components: {
			'rule-input': formInput,
			'rule-number': formNumber,
			'rule-select': formSelect,
			'rule-datepicker': formDatepicker,
			'draggable': draggable
		},
		methods: {
			// 激活对话框后操作
			opendDialog: function(){
				// 获得工具栏列表数据
				this.$http.post('/api/report/tool', {reportId: this.navInfo.id}, {emulateJSON: true}).then(response => {
					this.toolTableData = response.data.filter(obj => {
						if (!obj.deletedType){
							return true;
						}
					});
				}, response => {
					console.log('Ajax can not get the data from the server!!!');
				});
				// 获得字段数据
				this.$http.post('/api/report/field', {reportId: this.navInfo.id}, {emulateJSON: true}).then(response => {
					this.fieldData = response.data.filter(obj => {
						if (obj.display){
							return true;
						}
					});
				}, response => {
					console.log('Ajax can not get the data from the server!!!');
				});
			},
			// 关闭对话框->清空数据
			closeDialog: function(){
				this.toolTableData.splice(0, this.toolTableData.length);
				this.fieldData.splice(0, this.fieldData.length);
				this.toolComponents.splice(0, this.toolComponents.length);

			},
			// 取消编辑
			cancelEdit: function(formName){
				this.isEditable = false;
				this.$refs[formName].resetFields();
			},
			// 完成编辑
			finishedEdit: function(){
				this.$http.post('/api/report/tool/save', {reportId: this.navInfo.id, toolTableData: this.toolTableData.concat(this.toolTableDataDeleted)}).then(response => {
					this.isEditable = false;
					this.$notify({
						title: '成功',
						message: '数据已成功帮你保存，你可以继续进行你的low操作！',
						type: 'success'
					});
				}, response => {
					this.$notify({
						title: '错误',
						message: '垃圾服务器自己炸了，这锅我不背！',
						type: 'error'
					});
					console.log('Ajax can not get the data from the server!!!');
				});
			},

			// 添加字段规则
			addInfo: function(formName){
				this.$refs[formName].validate((valid) => {
					if (valid){
						console.log(valid);
						if (this.toolTableData.length > 0){
							let isExit = this.toolTableData.find((item) => {
								if (item.fieldId == this.formTool.fieldId){	
									this.$notify({
										title: '警告',
										message: '同一个字段你要填写两次？有意思吗？除非你是ZZ！',
										type: 'warning'
									});
									return true;
								}
							});
							if (!isExit){
								this.formTool.dsporder = this.toolTableData.length + 1;
								this.toolTableData.push(JSON.parse(JSON.stringify(this.formTool)));
								this.$refs[formName].resetFields();
							}
							return false;
						} else {
							this.formTool.dsporder = this.toolTableData.length + 1;
							this.toolTableData.push(JSON.parse(JSON.stringify(this.formTool)));
							this.$refs[formName].resetFields();
							return false;
						}
					}
				})				
			},

			// 绑定字段名称
			changeValue: function(value){
				var obj = this.fieldData.find((item) => {
					return item.fieldId == value;
				});
				console.log(this.formTool);
				this.formTool.reportId = obj.reportId;
				this.formTool.label = obj.label;
				this.formTool.fieldId = value;
				this.formTool.fieldName = obj.fieldName;
			},

			// 获得子组件的表单控件输入值
			getSearchValue: function(prop, value){
				this.search[prop] = value;
				console.log(this.search, prop, value);
			},

			// 拖拽表单项实现表格排序
			tabelSort: function(){
				this.drage = true;
				this.toolTableData.splice(0);
				this.toolComponents.forEach((element, index) => {
					element.toolInfo.dsporder = index;
					this.toolTableData.push(element.toolInfo);
				});
				this.drage = false;
			},

			/* 行内编辑 */
			// 编辑行内数据
			handleRowEdit: function(index, row){
				if (!row.isedit){
					// 缓存操作前数据
					this.cacheRows[index] = JSON.parse(JSON.stringify(row));
				} else {
					this.toolComponents.splice(0);
					console.log(this.toolComponents);
					this.toolTableData.forEach(element => {
						this.addComponents(element.type, element);
					});
				}
				row.isedit = !row.isedit;
			},
			// 取消行内编辑数据
			cancelRowEdit: function(index, row){
				// 获取缓存数据
				var cache = this.cacheRows[index];
				// 还原原始操作数据
				row.type = cache.type;
				// 删除缓存数据
				delete this.cacheRows[index];
				row.isedit = false;
			},
			// 删除字段表格数据
			handleRowDel: function(index, row){
				row.visible = false;
				row.deletedType = true;
				// 保留已存在数据库中数据-用于更新删除状态
				row.id && this.toolTableDataDeleted.push(this.toolTableData[index]);
				this.toolTableData.splice(index, 1);
			},
			/* 行内编辑 End*/

			// 动态添加组件
			addComponents: function(component, toolInfo){
				this.toolComponents.push({
					'component' : component,
					'toolInfo': toolInfo
				});
			},

			// 表单工具栏预览重置
			resetForm: function(){
				this.reset = !this.reset;
			}
		},
		watch: {
			// 监听父组件数组configRow状态
			'configRow': function(value){
				this.navInfo = value;
			},
			// 监听父组件isConfigTool状态
			'isConfigTool': function(value){
				this.isEditable = value;
			},
			// 监听子组件isEditable状态
			'isEditable': function(value){
				this.$emit('update:isConfigTool', value);
			},
			'toolTableData': function(value){
				console.log(value);
				if (!this.drage){
					this.toolComponents.splice(0);
					console.log(this.toolComponents);
					value.forEach(element => {
						this.addComponents(element.type, element);
					});
				}
			},
		}
	}
</script>

<style>
	.preview-tool-form{
	    border: solid #ccc 1px;
    	padding-top: 20px;
		margin-top: 20px;
	}
</style>